import React from 'react';
import { connect } from 'dva'

import moment from 'moment'
import Title from 'components/Title'
import Chart from 'components/Chart'

import Tools from 'utils/tools';

import { config } from 'utils';
const { scada } = config;
const {
  Token,
  Interval,
  StationIds,
  STypes,
  DTypes,
} = scada;

@connect(({ business }) => ({ ...business }))
class WaterStatistics extends React.Component {
  echartsConf = {
      chart: {
        type: 'Common2',
        columns: {
          seriesItems: [
            { name: '产销差率', field: 'radio', type: 'line', yAxisIndex: 1 },
            { name: '供水量', field: 'supply', type: 'bar', barWidth:'25%' },
            { name: '售水量', field: 'sell', type: 'bar', barWidth:'25%' },
            // { name: '产销差', field: 'subtract', type: 'bar', barWidth:'25%' },
          ],
          yAxis: [{ name: 'm³' }, { name: '%'}],
        },
        color: ['251, 212, 55', '68, 130, 255', '78, 203, 115', '134, 147, 243'],
        other: { showLegend: true },
      },
      dataResourceArr: ['SupplyWaterResourceUnique_Supply_Statistics', 'SellWaterResourceUnique_Sell_Statistics'],
      server: [
        {
            // 供水量
            type: 'business/querySupplyWater',
            payload: { type: 'Unique_Supply_Statistics', StationId: StationIds.supply.join(',') }
        }, {
            // 售水
            type: 'business/querySellWater',
            payload: { type: 'Unique_Sell_Statistics' }
        },
      ]
    };

  constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }
    this.state = {
      time,
      monthList: []
    };
  }

  componentWillMount(){
    this.init()
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      if (nextProps.defaultValue) {
        this.setState({
          time: nextProps.defaultValue
        }, () => {
          this.init()
        })
      }
    }
  }

  init = () => {
    this.setDateMonthList()
  }

  setDateMonthList = () => {
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time);
    this.setState({
      monthList
    }, () => {
      this.setDateECharts()
    })
  }

  // 图表
  setDateECharts = () => {
    const { echartsConf } = this;
    const { server } = echartsConf
    server.forEach(ele => {
      this.queryServer(ele);
    })
  }

  queryServer = async (server) => {
    const { monthList } = this.state;

    const { type, payload } = server;
    const { type: unType } = payload;

    let payloads = {};
    let servers = {};
    // 供水量
    if(type === 'business/querySupplyWater'){
      monthList.map((ele,idx) =>{
        Object.assign(payloads, payload,{
          Token,
          Interval,
          STypes,
          DTypes,
          Begin: moment(ele).startOf('month').unix(),
          End: moment(ele).endOf('month').unix(),
          type: `${unType}${idx}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      });
    }else{
      // 售水
      monthList.map((ele,idx) =>{
        // 售水量
        Object.assign(payloads, payload, {
          startDate: moment(ele).startOf('month').format('YYYY-MM-DD'),
          endDate: moment(ele).endOf('month').format('YYYY-MM-DD'),
          type: `${unType}${idx}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      })
    }
  }

  getData = (dataResourceArr, seriesItems) => {
    const { state, props } = this;
    const { monthList } = state;

    let resource = {}
    let time = []

    let supply = [],
        sell = [],
        subtract = [],
        radio = [];

    if(Array.isArray(dataResourceArr)){
      monthList.map((ele,idx) =>{
        // 供水
        const SupplyData = Tools.countSupplyWater(props[`${dataResourceArr[0]}${idx}`])
        supply.push(SupplyData)
        // 售水
        const SellData = Tools.countSellWater(props[`${dataResourceArr[1]}${idx}`])
        sell.push(SellData);
        // 产销差 （供水 - 售水）
        const SubtractData = SupplyData - SellData;
        subtract.push(SubtractData);
        // 产销差率
        const RadioData = SupplyData === 0 ? 0 : (SubtractData/SupplyData * 100).toFixed(2) * 1;
        radio.push(RadioData)

        time.push(moment(ele).format('M月'))
      })
    }

    seriesItems.forEach(ele => {
      const { field } = ele;
      Object.assign(ele, { data: eval(field)})
    })
    Object.assign(resource, { time, data: seriesItems })
    return resource;
  }

  // 图表渲染
  render() {
    const { props, state, echartsConf } = this;
    const { monthList } = state;
    const { chart, dataResourceArr } = echartsConf;
    const { type: chartType, columns, color, other } = chart;
    
    const Resource = this.getData(dataResourceArr, columns.seriesItems)

    return (<Title title={'产销情况分析'}>
        <Chart
          type={chartType}
          color={color}
          columns={columns}
          dataSource={Resource}
          other={other}
        />
      </Title>)
  }
}

export default WaterStatistics;
